import 'dart:async';
import 'dart:math';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:x3_base_package/x3_base_package.dart';

/// tab 配置
class BusinessTabNestedConfig {
  /// tab 项名称
  final String text;

  /// 组件
  /// 这里编写当前 tab 下的 StatefulWidget  尽量保持  autoKeep = true, BaseSearchBarController 是调用当前搜索框的组件
  final Widget Function(BaseSearchBarController) builder;

  /// 是否显示搜索栏
  final bool isShowSearchBar;

  BusinessTabNestedConfig({@required this.builder, @required this.text, this.isShowSearchBar = true});
}

/// 悬浮 tab 带搜索框组件
class BusinessTabNestedScrollView extends StatefulWidget {
  /// 头部组件
  final Widget headerWidget;

  /// tab 组
  final List<BusinessTabNestedConfig> tabs;

  /// 默认index
  final int selectedIndex;

  /// 搜索框内容
  final Map<int, String> searchBoxContent;

  const BusinessTabNestedScrollView({Key key, this.headerWidget, @required this.tabs, this.selectedIndex = 0, this.searchBoxContent = const <int, String>{}})
      : assert(tabs != null),
        assert(tabs.length >= 1),
        super(key: key);

  @override
  _BusinessTabNestedScrollViewState createState() => _BusinessTabNestedScrollViewState();
}

class _BusinessTabNestedScrollViewState extends State<BusinessTabNestedScrollView> {
  /// tab page
  BaseTabBarPage _baseTabBarPage;

  /// 当前 indexS
  int _currentIndex;

  /// 搜索栏控制器
  Map<int, BaseSearchBarController> _searchControllerList = {};

  /// 搜索栏
  Map<int, Widget> _searchBarList = {};

  /// 搜索栏控制器
  PageController _pageController;

  /// 是否隐藏 searchBar
  bool get isShowSearchBar => widget.tabs[_currentIndex].isShowSearchBar;

  /// 当前 悬浮栏高度
  double get currentPinnedHeight => getHeightHoverBar();

  @override
  void initState() {
    List<BaseTabConfig> _tabs = [];

    /// 数据分离
    for (int i = 0; i < widget.tabs.length; i++) {
      BusinessTabNestedConfig e = widget.tabs[i];
      String currSearchKey = widget.searchBoxContent[i] ?? '';

      /// 自动创建控制器
      BaseSearchBarController _controller = BaseSearchBarController(streamController: StreamController<BaseSearchBarConfigModel>(), searchKey: currSearchKey);
      _searchControllerList.addAll({i: _controller});

      /// 创建 搜索栏
      bool isShow = e.isShowSearchBar;
      Widget _searchBar = _buildSearchBarComponent(index: i, controller: _controller, show: isShow);
      _searchBarList.addAll({i: _searchBar});

      /// 创建TabView
      _tabs.add(BaseTabConfig(text: e.text, child: e.builder(_searchControllerList[i])));
    }

    /// 创建 tab
    _baseTabBarPage = BaseTabBarPage(_tabs);
    _baseTabBarPage.tabController.index = widget.selectedIndex;
    _currentIndex = _baseTabBarPage.tabController.index;

    /// 创建 search bar 控制器
    _pageController = PageController(initialPage: _currentIndex);

    /// 监听tab
    _baseTabBarPage.tabController.addListener(() {
      if (_baseTabBarPage.tabController.index == _baseTabBarPage.tabController.animation.value) {
        _currentIndex = _baseTabBarPage.tabController.index;
        _pageController.jumpToPage(_currentIndex);
        setState(() {});
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    List<String> titleList = widget.tabs.map((e) => e.text).toList();
    return BaseNestedScrollView(
      headerWidget: widget.headerWidget,
      pinnedWidget: BaseNestedScrollPinned(
        height: currentPinnedHeight,
        child: BaseCardComponent(
          child: Theme(
            data: Theme.of(context).copyWith(
              tabBarTheme: Theme.of(context).tabBarTheme.copyWith(labelPadding: EdgeInsets.symmetric(vertical: 4, horizontal: 10)),
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                _baseTabBarPage.buildTabBar(context, isScrollable: _searchBarList.length > 4 ? true : false, titleList: titleList),
                Container(
                  height: isShowSearchBar == true ? 40 : 0,
                  child: PageView(
                    controller: _pageController,
                    physics: NeverScrollableScrollPhysics(),
                    children: _searchBarList.values.toList(),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
      contentWidget: _baseTabBarPage.buildTabView(),
    );
  }

  /// 创建搜索框
  Widget _buildSearchBarComponent({@required int index, @required BaseSearchBarController controller, @required bool show}) {
    if (show == false) return SizedBox();
    return _TabSearchBar(key: Key(index.toString()), controller: controller);
  }

  /// 获取高度悬浮栏
  double getHeightHoverBar() {
    // tabBar 可滑动 则不计算高度了
    if (_searchBarList.length > 4) return isShowSearchBar == false ? 68 : 108;

    // 当tabBar不可滑动时则有可能出现溢出问题
    EdgeInsets _tabLabelPadding = (TabBarTheme.of(context).labelPadding ?? kTabLabelPadding);
    double _baseCardMarginWidth = 16.0 * 2;
    double _baseCardPaddingWidth = 12.0 * 2;
    double _tabLabelWidth = (MediaQuery.of(context).size.width - _baseCardMarginWidth - _baseCardPaddingWidth - _tabLabelPadding.horizontal) / 4 - 20;
    double _maxTabsHeight = 0.0;
    double textScaleFactor = MediaQueryData.fromWindow(window).textScaleFactor;
    TextStyle _labelStyle = Theme.of(context).tabBarTheme.labelStyle;
    _baseTabBarPage.tabs.forEach((element) {
      Size _tabLabelSize = BaseUtils.boundingTextSize(context, element.text, _labelStyle.copyWith(fontSize: _labelStyle.fontSize * textScaleFactor), maxWidth: _tabLabelWidth);
      _maxTabsHeight = max(_maxTabsHeight, _tabLabelSize.height);
    });
    double widgetHeight = _maxTabsHeight + _tabLabelPadding.vertical + _baseCardPaddingWidth + 0.0;
    return isShowSearchBar == false ? max(widgetHeight, 68.0) : max(widgetHeight, 68.0) + 40;
  }
}

/// 搜索框
class _TabSearchBar extends StatefulWidget {
  final BaseSearchBarController controller;

  const _TabSearchBar({Key key, @required this.controller}) : super(key: key);

  @override
  __TabSearchBarState createState() => __TabSearchBarState();
}

class __TabSearchBarState extends State<_TabSearchBar> with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Container(
      margin: EdgeInsets.only(top: 8),
      child: BaseSearchComponent(fillColor: BaseBodyTheme.greyBackgroundColor, value: widget.controller.searchKey, baseSearchBarController: widget.controller),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
